#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
        pid_t pid;
        char * message;
        int n;
        int exit_code;

        printf("fork program starting \n");
        pid = fork();
        switch(pid)
        {
            case -1:
                    perror("fork failed");
                    exit(1);
            case 0:
                    message = "This is the child";
                    n = 5;
                    exit_code = 38;
                    break;
            default:
                    message = "This is the parent";
                    n = 3;
                    exit_code = 0;
                    break;
        }

        for(;n>0;n--){
        
            printf("%s\n",message);
            sleep(1);
        }

        if(pid != 0){
            int status_val;
            pid_t child_pid;

            child_pid = wait(&status_val);

            printf("Child has finished:PID = %d\n",child_pid);
            if(WIFEXITED(status_val))//此处调用宏，如果子进程正常结束，它就取一个非零值。
                    printf("Child exited with cdoe %d\n",WEXITSTATUS(status_val));//如果WIFEXTED非零，它返回子进程的退出码。“未发现实际作用
            else 
                    printf("Child terminated abnormal\n");

        }
        exit(exit_code);

}
